package com.gepengjun.lims.config.shiro;

import com.google.code.kaptcha.Constants;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class KaptchaFilter extends AccessControlFilter {
    private static final Logger logger = LoggerFactory.getLogger(KaptchaFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest req, ServletResponse res) throws Exception {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        logger.info("KaptchaFilter.onAccessDenied:request.getMethod():"+request.getMethod());
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            //如果是get请求的话,继续,不做验证码  的验证
            logger.info("KaptchaFilter.onAccessDenied: return true");
            return true;
        }
        String kaptcha = request.getParameter("kaptchaCode");
        String validateCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (kaptcha == null || validateCode == null || !kaptcha.equalsIgnoreCase(validateCode)) {
            request.setAttribute("shiroLoginFailure", "kaptchaValidateFailed");
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        }
        return true;
    }
}
